
package Tables;
/*
 * SimpleTableDemo.java requires no other files.
 */
 

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import TableAdditions.CustomerTableAddition;
import TableAdditions.DailySalesTableAddition;
import TableAdditions.main;
import Utility.DatePicker;
import Utility.Personnel;
import Utility.Product;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.print.PageFormat;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class DailySalesTableInterface extends JPanel{
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    JButton dailySalesDeleteButton=new JButton("Sil");
    JTextField dateTextField = new JTextField();
    JButton datePickButton=new JButton("Tarih");
    int selectedBillId;
    final String[] newData=new String[9]; 					///////// for add new data to the table //only screen
    int counter=0;
    int selectedRow=-1;
    int[] billId;
    String date="";
    
    public DailySalesTableInterface() {
    	
    	//super(new GridBagLayout());
        String[] columnNames = {"Tarih","Personel Kodu","Müşteri Kodu",
                                "Ürün Kodu","Birim Fiyat","Promosyon","Miktar","Toplam","Nakit","Kalan"};  //colomn Names
        
        
  	 	
      

        for(int i=0;i<columnNames.length;i++)
        	model.addColumn(columnNames[i]);				//add columns
        
        addNewItem(date);
        
        JLabel newlineLabel = new JLabel("                                                                         " +
	    		"                                                                                                              ");
	   
        
        
        DefaultTableCellRenderer rdt = new DefaultTableCellRenderer(){
	    	public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,boolean hasFocus, int row, int column) {
	    		 Component c = 
	    			      super.getTableCellRendererComponent(table, value,
	    			                                          isSelected, hasFocus,
	    			                                          row, column);
	    	if (value == null)
	    	return super.getTableCellRendererComponent(table,
	    	value, isSelected, hasFocus, row, column);
	    	if (row != table.getRowCount()-1 )
	    		c.setFont(new Font("Helvetica Bold", Font.PLAIN,12));
	    	else
	    		c.setFont(new Font("Helvetica Bold", Font.BOLD,12));
	    	
	    	return c;
	    	}
	    	};
		    DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer(){
		    	public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,boolean hasFocus, int row, int column) {
		    		 Component c = 
		    			      super.getTableCellRendererComponent(table, value,
		    			                                          isSelected, hasFocus,
		    			                                          row, column);
		    	if (value == null)
		    	return super.getTableCellRendererComponent(table,
		    	value, isSelected, hasFocus, row, column);
		    	if (row != table.getRowCount()-1 )
		    		c.setFont(new Font("Helvetica Bold", Font.PLAIN,12));
		    	else
		    		c.setFont(new Font("Helvetica Bold", Font.BOLD,12));
		    	
		    	
		    	return c;
		    	}
		    	};
	        TableColumn column = new TableColumn();
	        for (int j = 0; j < columnNames.length; j++) {
	            column = table.getColumnModel().getColumn(j);
	            column.setPreferredWidth(15);
	            if(j<4)
	            	column.setCellRenderer(rdt);
	            else{
	            	rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
	            	column.setCellRenderer(rightRenderer);
	            	
	            }

	         
	          
	            
	        }
	        
	     
	    
	       
	    add(newlineLabel);

        
        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);
      //Add the scroll pane to this panel.
        add(scrollPane);
        
        table.addMouseListener(new MouseAdapter() {
			
			
			@Override
			public void mouseClicked(MouseEvent arg0) {
				// TODO Auto-generated method stub
				 if (table.getColumnSelectionAllowed()
		                    && !table.getRowSelectionAllowed()) {
					  
		                System.out.println("11111111111111");
		                // Column selection is enabled
		                // Get the indices of the selected columns
		                int[] vColIndices = table.getSelectedColumns();
		            } else if (!table.getColumnSelectionAllowed()
		                    && table.getRowSelectionAllowed()) {
		            	// System.out.println("222222222222");
		            	 selectedRow=table.getSelectedRow(); 
		            	 
		            	 if(selectedRow>-1){
		            		 selectedBillId=billId[selectedRow];
		            	 }
		            	 //System.out.println("selectedCustomer= "+customerNames[selectedRow]);
		                // Row selection is enabled
		                // Get the indices of the selected rows
		                int[] rowIndices = table.getSelectedRows();
		            } else if (table.getCellSelectionEnabled()) {
		                // Individual cell selection is enabled
		            	System.out.println("333333333333");

		                // In SINGLE_SELECTION mode, the selected cell can be retrieved using
		            	table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		                int rowIndex = table.getSelectedRow();
		                int colIndex = table.getSelectedColumn();
		              

		                // In the other modes, the set of selected cells can be retrieved using
		                table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		                table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

		                // Get the min and max ranges of selected cells
		                int rowIndexStart = table.getSelectedRow();
		                int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
		                int colIndexStart = table.getSelectedColumn();
		                int colIndexEnd = table.getColumnModel().getSelectionModel()
		                    .getMaxSelectionIndex();

		                // Check each cell in the range
		                for (int r=rowIndexStart; r<=rowIndexEnd; r++) {
		                    for (int c=colIndexStart; c<=colIndexEnd; c++) {
		                        if (table.isCellSelected(r, c)) {
		                        	System.out.println("4444444444444");
		                            // cell is selected
		                        }
		                    }
		                }
		            }
				
			}
		});
        
        
       
        
        
        
        dailySalesDeleteButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
			
				 if(selectedRow>-1){
            		

						Connection con = null;
				        Statement st = null;
				        ResultSet rs = null;

				        String url = "jdbc:mysql://localhost:3306/mydb";
				        String user = "root";
				        String password = "qweasdzxc";
				        Object[][] mydata=null;
				        try {
				            con = (Connection) DriverManager.getConnection(url, user, password);
				            st = (Statement) con.createStatement();
				            st.executeUpdate("DELETE from bill WHERE bill_id='"+selectedBillId+"'");
				            addNewItem(date);
				           
				            
				            
				            
				            con.close();
				        } catch (SQLException ex) {
				            Logger lgr = Logger.getLogger(main.class.getName());
				            lgr.log(Level.SEVERE, ex.getMessage(), ex);

				        } finally {
				            try {
				                if (rs != null) {
				                    rs.close();
				                }
				                if (st != null) {
				                    st.close();
				                }
				                if (con != null) {
				                    con.close();
				                }

				            } catch (SQLException ex) {
				                Logger lgr = Logger.getLogger(main.class.getName());
				                lgr.log(Level.WARNING, ex.getMessage(), ex);
				            }
				        }
						/////////////////////////////////////////
					 
					 
            	 }

				
			}
			
			
		});
        
        
        datePickButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e){
			    			final JFrame startFrame = new JFrame();
							date=new DatePicker(startFrame).setPickedDate();
							date=arrangeDate(date);
				            addNewItem(date);	
			}
		});
        
        JButton PrintTableBtn = new JButton("Yazdır");
	    PrintTableBtn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				  PageFormat documentPageFormat = new PageFormat();
				    documentPageFormat.setOrientation(PageFormat.PORTRAIT);
				    MessageFormat header = new MessageFormat("Günlük Satış Tablosu");
				    try {
				    	//MessageFormat format = new MessageFormat("{0}");
				    	MessageFormat format = new MessageFormat("Sayfa {0,number,integer}");
				        table.print(JTable.PrintMode.FIT_WIDTH, header, format);
				    } catch (java.awt.print.PrinterException e1) {
				        System.err.format("Cannot print %s%n", e1.getMessage());
				    }
			
			}
		});
	    
	    //add(PrintTableBtn);
        
        addItem(dateTextField,1,1,1,1,GridBagConstraints.CENTER);
        addItem(datePickButton,2,1,1,1,GridBagConstraints.CENTER);
        addItem(PrintTableBtn,3,1,1,1,GridBagConstraints.CENTER);	//call the addItem method and add in panel
      
        
        
       
       
    }
    
    public void addNewItem(String date){
    	deleteAllRows(model);
    	
    	Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        String url = "jdbc:mysql://localhost:3306/mydb";			/////connection setups
        String user = "root";
        String password = "qweasdzxc";
        Object[][] mydata=null;
        try {
            con = (Connection) DriverManager.getConnection(url, user, password);		//create connections and setups
            st = (Statement) con.createStatement();
            
            if(date.equals("")){
            	rs=st.executeQuery("SELECT * from bill WHERE bill_date=curdate()");		//get query to the rs
            }
            else{
            	rs=st.executeQuery("SELECT * from bill WHERE bill_date='"+date+"'");
            }
            int i=0;
            counter=0;
            while(rs.next())
            	++counter;
            
            billId= new int[counter+1];
            
            int amount,amountsum=0,promotion=0,promotionSum=0;
            float specialPrice,specialPriceSum=0,billCost,billCostSum=0,credit=0,creditSum=0,cash=0,cashSum=0;
            java.text.NumberFormat nf = new java.text.DecimalFormat("0.00");
            
            if(counter>0){
            	rs.first();
            	mydata=new Object[counter+1][10];
            	billId[i]=rs.getInt("bill_id");
            	mydata[i][0]=rs.getString("bill_date");							///Add Datas to the table on screen // from database
        		mydata[i][1]=rs.getString("personel_id");
        		mydata[i][2]=rs.getString("customer_code");
        		mydata[i][3]=rs.getString("product_id");
        		mydata[i][4]=rs.getString("special_price");
        		mydata[i][6]=rs.getString("bill_amount");
        		mydata[i][8]=nf.format(rs.getFloat("bill_cash"));
        		mydata[i][9]=nf.format(rs.getFloat("bill_credit"));			//////////////////////////////////    ||
        		mydata[i][7]=nf.format(rs.getFloat("bill_cost"));
        		amount=rs.getInt("bill_amount");
        		amountsum+=amount;
        		specialPrice=rs.getFloat("special_price");
        		specialPriceSum+=specialPrice;
        		billCost=rs.getFloat("bill_cost");
        		billCostSum+=billCost;
        		cash=rs.getFloat("bill_cash");
        		cashSum+=cash;
        		credit=billCost-cash;
        		creditSum+=credit;
        		promotion=(int) (((amount*specialPrice)-billCost)/specialPrice);
        		mydata[i][5]=promotion;
        		promotionSum+=promotion;
        		++i;
            
            
            while(rs.next())								
            {
            	billId[i]=rs.getInt("bill_id");
            	mydata[i][0]=rs.getString("bill_date");							///Add Datas to the table on screen // from database
        		mydata[i][1]=rs.getString("personel_id");
        		mydata[i][2]=rs.getString("customer_code");
        		mydata[i][3]=rs.getString("product_id");
        		mydata[i][4]=rs.getString("special_price");
        		mydata[i][6]=rs.getString("bill_amount");
        		mydata[i][8]=nf.format(rs.getFloat("bill_cash"));
        		mydata[i][9]=nf.format(rs.getFloat("bill_credit"));			//////////////////////////////////    ||
        		mydata[i][7]=nf.format(rs.getFloat("bill_cost"));
        		amount=rs.getInt("bill_amount");
        		amountsum+=amount;
        		specialPrice=rs.getFloat("special_price");
        		specialPriceSum+=specialPrice;
        		billCost=rs.getFloat("bill_cost");
        		billCostSum+=billCost;
        		cash=rs.getFloat("bill_cash");
        		cashSum+=cash;
        		credit=billCost-cash;
        		creditSum+=credit;
        		promotion=(int) (((amount*specialPrice)-billCost)/specialPrice);
        		mydata[i][5]=promotion;
        		promotionSum+=promotion;
        		++i;
        
            }
            
            rs= st.executeQuery("Select * FROM personel where activity=1");
            
            int personelCounter=0;
            
            while(rs.next()){
            	personelCounter++;
            }
            
            rs.first();
            int count=0;
            Personnel[] personels = new Personnel[personelCounter];
            personels[count]=new Personnel();
            personels[count].setPersonnelId(rs.getInt("personel_id"));
            personels[count].setPersonnelName(rs.getString("personel_name"));
            count++;
            
            while(rs.next()){
            	personels[count]=new Personnel();
                personels[count].setPersonnelId(rs.getInt("personel_id"));
                personels[count].setPersonnelName(rs.getString("personel_name"));
                count++;
            }
            
            
            for(int k=0;k<counter;k++){
            	for(int j=0;j<personelCounter;j++){
            		if(mydata[k][1].toString().equals(Integer.toString(personels[j].getPersonnelId()))){
            			mydata[k][1]=personels[j].getPersonnelName();
            		}
            	}
            }
            
            
            rs= st.executeQuery("Select * FROM product where activity=1");
            
            int productCounter=0;
            
            
            while(rs.next()){
            	productCounter++;
            }
            
            rs.first();
            count=0;
            Product[] products = new Product[productCounter];
            products[count]=new Product();
            products[count].setProductId(rs.getInt("product_id"));
            products[count].setProductCode(rs.getString("product_code"));
            count++;
            
            while(rs.next()){
            	products[count]=new Product();
                products[count].setProductId(rs.getInt("product_id"));
                products[count].setProductCode(rs.getString("product_code"));
                count++;
            }
            
            
            for(int k=0;k<counter;k++){
            	for(int j=0;j<productCounter;j++){
            		System.out.println("mydata="+mydata[k][3].toString()+" vs  productId= "+products[j].getProductId());
            		if(mydata[k][3].toString().equals(Integer.toString(products[j].getProductId()))){
            			System.out.println("product found!!!!!!!");
            			mydata[k][3]=products[j].getProductCode();
            		}
            	}
            }
            
            mydata[i][0]="Toplam";
            mydata[i][6]=amountsum;
            //mydata[i][4]=nf.format(specialPriceSum);
            mydata[i][7]=nf.format(billCostSum);
            mydata[i][9]=nf.format(creditSum);
            mydata[i][8]=nf.format(cashSum);
            
            
            
            }
            con.close();
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(main.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(main.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }
        
        table.setPreferredScrollableViewportSize(new Dimension(920, 600));
        table.setFillsViewportHeight(true);
        
        if(counter>0){
        	for(int b=0;b<mydata.length;b++)	{	
        		model.addRow(mydata[b]);		//add arrays to the table on screen
        		//System.out.println(b);
        	}

        }
   
        
	
  
     }	
     
    /**
     *This method is good to use GridBagLayout simple
     * 
     */
    private void addItem(JComponent c, int x, int y, int width, int height, int align) {
        GridBagConstraints gc = new GridBagConstraints();
        gc.gridx = x;
        gc.gridy = y;
        gc.gridwidth = width;
        gc.gridheight = height;
        gc.weightx = 100.0;
        gc.weighty = 100.0;
        gc.insets = new Insets(5, 5, 5, 5);
        gc.anchor = align;
        gc.fill = GridBagConstraints.NONE;
        add(c, gc);
      }
    
    protected String arrangeDate(String text) {
		String arrangedDate=text;
		int dashCounter=0;
		String day="";
		String month="";
		String year="";
		String temp="";
		
		for(int b=0;b<arrangedDate.length();b++){
			char tmp= arrangedDate.charAt(b);
			if(tmp=='-'){
				if(dashCounter==0){
					day=temp;
					temp="";
				}
				if(dashCounter==1){
					month=temp;
					temp="";
				}
				dashCounter++;
			}
			else{
				temp=temp+tmp;
			}
			year=temp;
		}
		
		arrangedDate=year+"-"+month+"-"+day;
		
		return arrangedDate;
	}

    
    public static void deleteAllRows(final DefaultTableModel model) {
	    for( int i = model.getRowCount() - 1; i >= 0; i-- ) {
	        model.removeRow(i);
	    }
	}

}